package com.company.pangu.aliyun.pns.client;

import cn.hutool.core.util.ObjectUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dypnsapi.model.v20170525.GetMobileRequest;
import com.aliyuncs.dypnsapi.model.v20170525.GetMobileResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.company.nuwa.common.utils.JsonUtils;
import com.company.pangu.aliyun.pns.config.PnsConfig;
import com.company.pangu.aliyun.pns.request.PnsGetMobileRequest;
import com.company.pangu.aliyun.pns.response.PnsGetMobileResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * <p>阿里云号码认证服务</p >
 * https://help.aliyun.com/document_detail/84540.html?spm=a2c4g.11186623.6.542.57dd360cqtAPhZ
 *
 * @author Nikola Tesla
 * @version 1.0
 * @date 2020/09/25 11:48
 */
@Slf4j
public class PnsClient {

    private final IAcsClient pnsAcsClient;

    public PnsClient(PnsConfig pnsConfig) {
        IClientProfile profile = DefaultProfile.getProfile(
                ObjectUtil.defaultIfBlank(pnsConfig.getRegionId(), "cn-hangzhou"),
                pnsConfig.getAccessKeyId(),
                pnsConfig.getAccessKeySecret()
        );
        this.pnsAcsClient = new DefaultAcsClient(profile);
    }

    /**
     * 一键登录，获取手机号
     * <p>
     * https://help.aliyun.com/document_detail/121111.html?spm=a2c4g.11186623.6.552.61137861NwYRyA
     *
     * @param request
     * @return
     */
    public PnsGetMobileResponse getMobile(PnsGetMobileRequest request) {
        com.aliyuncs.dypnsapi.model.v20170525.GetMobileRequest mobileRequest = new GetMobileRequest();
        mobileRequest.setAccessToken(request.getAccessToken());
        try {
            log.info("PnsClient#getMobile request={}", request);
            GetMobileResponse response = pnsAcsClient.getAcsResponse(mobileRequest);
            log.info("PnsClient#getMobile response={}", JsonUtils.objectToJson(response));
            return PnsGetMobileResponse.builder()
                    .mobile(response.getGetMobileResultDTO().getMobile())
                    .build();
        } catch (ClientException e) {
            log.error("PnsClient#getMobile", e);
            throw new RuntimeException("invoke ali get mobile error");
        }
    }

    /**
     * shut down
     */
    public void shutdown() {
        if (Objects.nonNull(pnsAcsClient)) {
            pnsAcsClient.shutdown();
        }
    }

}
